const mongoose = require("mongoose");
// const bcrypt = require('bcryptjs');
const { nanoid } = require('nanoid');
const {url} = require("../utils/url");

const muserSchema = new mongoose.Schema({
    nickname: {
        type: String,
    },
    username: {
        type: String,
        unique: true, // 确保用户名唯一
        required: true,
    },
    roles: [{ type: mongoose.Schema.Types.ObjectId, ref: 'role' }],
    order:{
        type: Number,
        default:0
    },
    disabled:{
        type: Boolean,
        default:false
    },
    avatar: {
        type: String,
        default: `${url}nan.png`
    },
    phone: {
        type: String,
    },
    email: {
        type: String,
    },
    sex:{
        type: Number,
        default:2
    },
    password: {
        type: String,
        default:'111'
    },
});

// 在保存前生成随机用户名和加密密码
muserSchema.pre('save', async function (next) {
    const user = this;
    // 如果是新用户，则生成随机用户名
    if(this.isNew) {
        let generatedUsername;
        do {
            generatedUsername = `康斐尔_${nanoid(8)}`; // 生成一个随机的用户名
            // 检查生成的用户名是否已经存在
            const existingUser = await this.constructor.findOne({ nickname: generatedUsername });
            if (!existingUser) break;
        } while (true);

        user.nickname = generatedUsername;

    }

    // // 如果密码被修改或设置，则加密密码
    // if (user.isModified('password')) {
    //     const salt = await bcrypt.genSalt(10);
    //     user.password = await bcrypt.hash(user.password, salt);
    // }

   await next();
});


const muser = mongoose.model("muser", muserSchema);
module.exports = {
    muser
};
